<script setup lang="ts">
definePageMeta({
    layout: 'whitebg',
    title: '修改密码',
    i18n: 'menu.updatePwd',
})
const { t } = useI18n();
const show = ref(false);
const phone = ref('+6613887678787');
onMounted(() => {
    nextTick(() => {
        phoneRefs.value = phoneRefs.value.slice(0, 4);
    });
});
// 6位数的验证码
const verifyCode = ref(["", "", "", "", "", ""]);
// 中间4位号码
const centerPhone = ref(["", "", "", ""]);
const phoneRefs = ref([]);
const codeRefs = ref([]);
const phoneIndex = ref(0);
const codeIndex = ref(0);
const isError = ref(false);
const getCode = ref(false);
// 弹窗聚焦事件
watch(() => show.value, (val) => {
    if (val) {
        console.log(111111);

        nextTick(() => {
            phoneRefs.value[0]?.focus();
        });
    }
});
// 验证码焦事件
watch(() => getCode.value, (val) => {
    if (val) {
        nextTick(() => {
            codeRefs.value[0]?.focus();
        });
    }
});
// 输入
const onInput = (index: number, type: number) => {
    if (type == 1) {
        const val = verifyCode.value[index];
        if (val&&/^\d$/.test(val)) {
            // 移动焦点到下一个输入框
            if (index < 5) {
                nextTick(() => {
                    codeRefs.value[index + 1]?.focus();
                });
            }
        } else {
            verifyCode.value[index] = "";
        }
    } else {
        const val = centerPhone.value[index];
        if (/^\d$/.test(val)) {
            // 移动焦点到下一个输入框
            if (index < 3) {
                nextTick(() => {
                    phoneRefs.value[index + 1]?.focus();
                });
            }
        } else {
            centerPhone.value[index] = "";
        }
    }

};
// 删除
const onDelete = (index: number, type: number) => {
    if (type == 1) {
        if (verifyCode.value[index] === "" && index > 0) {
            nextTick(() => {
                codeRefs.value[index - 1]?.focus();
            });
        }
    } else {
        if (centerPhone.value[index] === "" && index > 0) {
            nextTick(() => {
                phoneRefs.value[index - 1]?.focus();
            });
        }
    }

};


const onlyNumber = (event: KeyboardEvent) => {
    const key = event.key;
    if (!/^\d$/.test(key)) {
        event.preventDefault(); // 阻止非数字输入
    }
};
// 弹窗取消事件
const onCancel = () => {
    centerPhone.value = ['', '', '', ''];
    isError.value = false;
    show.value = false;
};
// 打开弹窗确认事件
const handleBeforeClose = (action: string, done: () => void) => {
    if (action === 'confirm') {
        if (centerPhone.value.every(code => code !== '')) {
            const code = centerPhone.value.join('');
            console.log('验证码：', code);
            getCode.value = true
            onCancel()
            // done(); // 确认关闭
        } else {
            isError.value = true;
        }
    } else {
        onCancel()
        // done(); // 确认关闭
    }
};
// 倒计时相关的数据
const countdown = ref(60);
const isCounting = ref(false);
// 获取验证码
const getVerifyCode = () => {
    if (isCounting.value) return;

    isCounting.value = true;
    let timer = setInterval(() => {
        if (countdown.value > 0) {
            countdown.value--;
        } else {
            clearInterval(timer);
            isCounting.value = false;
            countdown.value = 60;
        }
    }, 1000);

};
</script>

<template>
    <div mx-auto text-center text-16 text-dark dark:text-white>
        <div class="mt-20 mb-10">
            <div class="my-10 font-bold color-#30303c">{{ getCode ? countdown == 60 ? t('my_page.setting.updatePwd.getCode') : t('my_page.setting.updatePwd.inputCode')  : t('my_page.setting.updatePwd.phoneValid') }}</div>
            <div class="text-12 color-#6c6f7b">{{ getCode ? countdown == 60 ? t('my_page.setting.updatePwd.placeGetCode') : t('my_page.setting.updatePwd.sendCode') :t('my_page.setting.updatePwd.placeValidCode') }}
            </div>
            <div class="text-12">{{ getCode ? phone : '' }}</div>
        </div>
        <!-- 手机号 -->
        <van-form class="outForm mb-10 mx-5" v-if="!getCode">
            <van-cell-group inset>
                <van-field v-model="phone" name="phone" label="+66" :rules="[{ required: true }]" />
            </van-cell-group>
            <div class="mt-20 w-180 mx-auto">
                <van-button block round type="primary" native-type="button" @click="show = true">
                   {{t('my_page.setting.updatePwd.getCode') }}
                </van-button>
            </div>
        </van-form>
        <!-- 外层输入验证码 -->
        <div v-else>
            <van-form class="dialog mb-10 mx-20 flex justify-between items-center">
                <template v-for="(val, index) in verifyCode" :key="index">
                    <van-cell-group inset>
                        <van-field ref="codeRefs" v-model="verifyCode[index]" type="tel" maxlength="1"
                            :class="{ 'error-border': isError && verifyCode[index] === '' }" input-align="center"
                            class="verify-input" @input="onInput(index, 1)" @keypress="onlyNumber"
                            @keydown.delete="onDelete(index, 1)" @focus="codeIndex = index" />
                    </van-cell-group>
                </template>
            </van-form>
            <div class="color-[var(--c-primary)] text-right text-12 pr-20" @click="getVerifyCode">
                <div>
                    <div v-if="!isCounting">    {{t('my_page.setting.updatePwd.getCode') }}</div>
                    <div v-else>{{ countdown }}s     {{t('my_page.setting.updatePwd.retry') }}</div>
                </div>
            </div>
        </div>
        <!-- 弹窗 -->
        <van-dialog v-model:show="show" :title="t('my_page.setting.updatePwd.security')" show-cancel-button  class="dialog" :overlayStyle="{  backgroundColor: 'rgba(0, 0, 0, 0.3)'}" width="75%"
            :before-close="handleBeforeClose">
            <div class="text-12 my-10 px-12 color-#666470"> {{t('my_page.setting.updatePwd.center4') }}</div>
            <div class="text-14 my-10 color-#0d0c11">+66 138****8787</div>
            <van-form class="mb-10 mx-30 flex justify-between items-center">
                <template v-for="(val, index) in centerPhone" :key="index">
                    <van-cell-group inset>
                        <van-field ref="phoneRefs" v-model="centerPhone[index]" type="tel" maxlength="1"
                            :class="{ 'error-border': isError && centerPhone[index] === '' }" input-align="center"
                            class="verify-input" @input="onInput(index, 2)" @keypress="onlyNumber"
                            @keydown.delete="onDelete(index, 2)" @focus="phoneIndex = index" />
                    </van-cell-group>
                </template>
            </van-form>
        </van-dialog>
      
    </div>
</template>
<style lang="css" scoped>
::v-deep .van-field__label {
    width: 30px;
}

::v-deep .dialog .van-cell {
    width: 46px;
    border-radius: 9px;
    border: 1px solid #f2f2f2;
    background: #f2f1f7;
}

::v-deep .dialog .van-cell.error-border {
    border: 1px solid #ff4d4f !important;
}

::v-deep .outForm .van-cell-group--inset {
    background: transparent;
}

::v-deep .outForm .van-cell {
    background: #f9fafc;
    color: #aab2bb;
    margin: 10px 0;
    padding: 10px 12px;
    border-radius: 8px;
    border: 1px solid #f0f1f3;
}

::v-deep .outForm .van-field__control {
    color: #a1a1aa;
}
::v-deep .outForm .van-field__label {
    color: #a1a1aa;
}
</style>